package com.logistics.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.logistics.common.TenantContextHolder;
import com.logistics.dto.VehicleCreateRequest;
import com.logistics.entity.Vehicle;
import com.logistics.mapper.VehicleMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 车辆服务
 * 车辆属于公司（tenant_id），所有站点共享可见
 */
@Service
public class VehicleService {
    
    private final VehicleMapper vehicleMapper;
    
    public VehicleService(VehicleMapper vehicleMapper) {
        this.vehicleMapper = vehicleMapper;
    }
    
    /**
     * 创建车辆
     */
    public Vehicle createVehicle(VehicleCreateRequest request) {
        Long tenantId = TenantContextHolder.getTenantId();
        
        // 检查车牌号是否重复（公司内唯一）
        LambdaQueryWrapper<Vehicle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Vehicle::getTenantId, tenantId)
               .eq(Vehicle::getPlateNumber, request.getPlateNumber());
        if (vehicleMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("车牌号已存在");
        }
        
        Vehicle vehicle = new Vehicle();
        vehicle.setTenantId(tenantId);
        vehicle.setPlateNumber(request.getPlateNumber());
        vehicle.setVehicleType(request.getVehicleType());
        vehicle.setBrandModel(request.getBrandModel());
        vehicle.setVehicleSource(request.getVehicleSource());
        vehicle.setLoadCapacity(request.getLoadCapacity());
        vehicle.setVolumeCapacity(request.getVolumeCapacity());
        vehicle.setPurchaseDate(request.getPurchaseDate());
        vehicle.setInsuranceExpireDate(request.getInsuranceExpireDate());
        vehicle.setInspectionExpireDate(request.getInspectionExpireDate());
        vehicle.setVehicleStatus(request.getVehicleStatus() != null ? request.getVehicleStatus() : "AVAILABLE");
        vehicle.setRemark(request.getRemark());
        
        // 车主信息
        vehicle.setOwnerName(request.getOwnerName());
        vehicle.setOwnerPhone(request.getOwnerPhone());
        vehicle.setOwnerIdCard(request.getOwnerIdCard());
        vehicle.setOwnerLicenseNumber(request.getOwnerLicenseNumber());
        vehicle.setOwnerLicenseType(request.getOwnerLicenseType());
        vehicle.setOwnerLicenseExpireDate(request.getOwnerLicenseExpireDate());
        vehicle.setOwnerAddress(request.getOwnerAddress());
        
        vehicleMapper.insert(vehicle);
        
        return vehicle;
    }
    
    /**
     * 分页查询车辆列表
     * 车辆属于公司，所有站点共享可见
     */
    public IPage<Vehicle> getVehicleList(Integer current, Integer size, String vehicleStatus, String keyword) {
        Page<Vehicle> page = new Page<>(current, size);
        
        Long tenantId = TenantContextHolder.getTenantId();
        
        LambdaQueryWrapper<Vehicle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Vehicle::getTenantId, tenantId);
        
        if (StringUtils.hasText(vehicleStatus)) {
            wrapper.eq(Vehicle::getVehicleStatus, vehicleStatus);
        }
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w
                .like(Vehicle::getPlateNumber, keyword)
                .or()
                .like(Vehicle::getBrandModel, keyword)
            );
        }
        
        wrapper.orderByDesc(Vehicle::getCreateTime);
        
        return vehicleMapper.selectPage(page, wrapper);
    }
    
    /**
     * 获取车辆详情
     */
    public Vehicle getVehicleById(Long id) {
        return vehicleMapper.selectById(id);
    }
    
    /**
     * 更新车辆
     */
    public void updateVehicle(Long id, VehicleCreateRequest request) {
        Vehicle vehicle = vehicleMapper.selectById(id);
        if (vehicle == null) {
            throw new RuntimeException("车辆不存在");
        }
        
        vehicle.setVehicleType(request.getVehicleType());
        vehicle.setBrandModel(request.getBrandModel());
        vehicle.setVehicleSource(request.getVehicleSource());
        vehicle.setLoadCapacity(request.getLoadCapacity());
        vehicle.setVolumeCapacity(request.getVolumeCapacity());
        vehicle.setPurchaseDate(request.getPurchaseDate());
        vehicle.setInsuranceExpireDate(request.getInsuranceExpireDate());
        vehicle.setInspectionExpireDate(request.getInspectionExpireDate());
        vehicle.setVehicleStatus(request.getVehicleStatus());
        vehicle.setRemark(request.getRemark());
        
        // 车主信息
        vehicle.setOwnerName(request.getOwnerName());
        vehicle.setOwnerPhone(request.getOwnerPhone());
        vehicle.setOwnerIdCard(request.getOwnerIdCard());
        vehicle.setOwnerLicenseNumber(request.getOwnerLicenseNumber());
        vehicle.setOwnerLicenseType(request.getOwnerLicenseType());
        vehicle.setOwnerLicenseExpireDate(request.getOwnerLicenseExpireDate());
        vehicle.setOwnerAddress(request.getOwnerAddress());
        
        vehicleMapper.updateById(vehicle);
    }
    
    /**
     * 删除车辆
     */
    public void deleteVehicle(Long id) {
        vehicleMapper.deleteById(id);
    }
}

